package com.fzu.normalservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fzu.commonutil.util.ApiException;
import com.fzu.commonutil.util.PageVO;
import com.fzu.commonutil.entity.AddressBook;
import com.fzu.commonutil.entity.User;
import com.fzu.commonutil.mapper.AddressBookMapper;
import com.fzu.normalservice.service.AddressBookService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fzu.normalservice.util.CommonUtil;
import com.fzu.normalservice.util.ErrorEnum;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zyq
 * @since 2023-03-26
 */
@Service
@RequiredArgsConstructor
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {
    private final AddressBookMapper addressBookMapper;

    @Override
    public PageVO ListAll(AddressBook addressBook, User user, Integer pageNum, Integer pageSize) {
        // 构造分页参数
        Page<AddressBook> pageRequest = new Page<>(pageNum, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.eq(AddressBook::getUserId, user.getId());

        // 添加手机号码查询条件（不为空则添加筛选条件）
        String phone = addressBook.getPhone();
        if (StringUtils.isNotBlank(phone)) {
            queryWrapper.eq(AddressBook::getPhone, phone);
        }
        // 添加姓名查询条件（不为空则添加筛选条件）
        String name = addressBook.getName();
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.eq(AddressBook::getName, name);
        }

        IPage<AddressBook> page = addressBookMapper.selectPage(pageRequest, queryWrapper);
        return PageVO.convert(page);
    }

    @Override
    public void updateAddressBook(AddressBook addressBook) {
        // 更新是根据id确定记录的，所以必须对id进行非空判断
        if (addressBook.getId() == null){
            throw new ApiException("ID值不能为空");
        }
        String phone = addressBook.getPhone();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(phone) && !CommonUtil.validPhone(phone)) {
            throw new ApiException(String.valueOf(ErrorEnum.PHONE_FORMAT_ERROR));
        }
        super.updateById(addressBook);
    }

    @Override
    public void deleteAddressBook(Integer id) {
        super.removeById(id);
    }
}
